import os
import platform

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import tempfile
from utils.log_manager import my_logger
class DriverManager():

    def __init__(self,name='chrome'):
        if name == 'chrome':
            # 获取当前文件的目录
            base_dir = os.path.dirname(os.path.abspath(__file__))
            # 构造相对路径
            if platform.system() == "Windows":
                chrome_driver_path = os.path.join(base_dir,  'chromedriver.exe')
            elif platform.system() == "Darwin":  # macOS 系统返回的是 "Darwin"
                chrome_driver_path = os.path.join(base_dir,  'chromedriver')
            else:
                raise Exception("不支持的操作系统")

            my_logger.logger.debug("chrome_driver,路径:{}",chrome_driver_path)
            service = Service(chrome_driver_path)
            options = webdriver.ChromeOptions()
            options.add_argument('--ignore-ssl-errors=yes')
            options.add_argument('--ignore-certificate-errors')
            # 临时用户数据目录，避免使用本地配置
            user_data_dir = tempfile.mkdtemp()
            options.add_argument(f"--user-data-dir={user_data_dir}")
            # 禁用各种密码提示
            prefs = {
                "credentials_enable_service": False,  # 禁用凭据服务
                "profile.password_manager_enabled": False,  # 禁用密码管理器
                "profile.default_content_setting_values.notifications": 2  # 禁用浏览器通知弹窗
            }
            options.add_experimental_option("prefs", prefs)
            # 禁用“密码泄露”检测（重点）
            options.add_argument("--disable-features=PasswordCheck")
            my_logger.logger.debug("初始化chrome...")
            self.d = webdriver.Chrome(options=options, service=service)
        elif name == 'firefox':
            self.d = webdriver.Firefox()


# 初始化driver对象
driver = DriverManager().d
driver.implicitly_wait(5)
